import router from "./router"
import cache from '@/utils/cache'
import { useLoginStore } from "@/store/login"
import message from "@/utils/message";
import { start, done } from "@/utils/nprogress"

const whiteList = ["/login"];

router.beforeEach(async (to, from, next) => {
    start()
    let loginStore = useLoginStore()
    let token = cache.getCache('token')
    if (token) {
        if (to.path === '/login') {
            next({ path: "/" });
            done();
        } else {
            let username = loginStore.usernameGetter
            if (username) {
                next()
            } else {
                try {
                    await loginStore.getUserInfo()
                    await loginStore.getMenus()
                    next({ ...to, replace: true })
                } catch (error) {
                    loginStore.reset()
                    message.error(error || "未知错误");
                    next(`/login?redirect=${to.path}`);
                    done();
                }
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next();
        } else {
            next(`/login?redirect=${to.path}`);
        }
    }
})

router.afterEach(() => {
    done();
});